package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.logFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

public class Strength {

	private String _sid;
	Properties props;
	private static List<Long> canUseCard = new ArrayList<Long>();
	static {
		for (int id : new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
				16, 18, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 61,
				62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 91, 92, 93, 94, 95, 96,
				97, 98, 99, 100, 101, 102, 103, 141, 147, 153, 159 }) {
			canUseCard.add((long) id);
		}
	}

	public Strength(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.contains("canUseStrengthCard")) {
			canUseCard.clear();
			String cardIds = props.getProperty("canUseStrengthCard");
			for (String id : cardIds.split(",")) {
				canUseCard.add(Long.parseLong(id));
			}

		}
		System.out.println("canUseCard:" + canUseCard);
	}

	public void strength(int level, long cardId) throws IOException {
		Map map = httpRequestWithLogFile(_sid, "user.php", "GetUserinfo", "",
				logFile);
		Map data = (Map) map.get("data");
		System.out.println(data.get("NickName").toString());

		Map cardsResult = httpRequestWithLogFile(_sid, "card.php",
				"GetUserCards", "", logFile);
		int status = (Double.valueOf(cardsResult.get("status").toString())).intValue();
		if (status == 0) {
			System.err.println("获取卡牌失败！");
			System.out.println(cardsResult);
			return;
		}
		List cardlist = (List) ((Map) cardsResult.get("data")).get("Cards");

		long userCardId = -1;
		for (Object obj : cardlist) {
			Map card = (Map) obj;
			int cLevel = (int) Double.parseDouble(card.get("Level").toString());
			long cId = (long) Double.parseDouble(card.get("CardId").toString());
			if (cLevel == level && cId == cardId) {
				System.out.println("已找到匹配项：" + card + " 是否确认？");
				String userConfirm = readLineFromConsole();
				if (!"y".equals(userConfirm)) {
					System.out.println("用户主动退出。");
					return;
				}
				userCardId = (long)Double.parseDouble(card.get("UserCardId").toString());
			}
		}
		if (userCardId == -1) {
			System.err.println("未找到匹配的卡，请重新确认");
			System.out.println(cardlist);
			return;
		}

		// 找到了待升级的卡牌，开始预览
		List<Long> toUseStrengthUserCardId = new ArrayList<Long>();

		for (Object obj : cardlist) {
			Map card = (Map) obj;
			int cLevel = (int) Double.parseDouble(card.get("Level").toString());
			long cId = (long) Double.parseDouble(card.get("CardId").toString());
			long toAddUserCardId = (long) Double.parseDouble(card.get(
					"UserCardId").toString());
			if (canUseCard.contains(cId) && cLevel == 0) {
				toUseStrengthUserCardId.add(toAddUserCardId);
				System.out.println("Add: " + card);
			}
		}
		// 计算升级经验值
		String content = calculateContent(userCardId, toUseStrengthUserCardId);
		List<Long> backUpUserCardId = new ArrayList<Long>();
		Map previewResult = httpRequestWithLogFile(_sid, "streng.php",
				"CardPreview", content, logFile);
		int currentLevel = 0;
		currentLevel = (int) Double.parseDouble(returnData(previewResult).get(
				"CardLevel").toString());
		while (currentLevel == 10) {
			// 如果到10级了则递减最后一个卡片放到backUp
			// 回到9级时再从backUp拿一个即可。
			Long backUp = toUseStrengthUserCardId
					.remove(toUseStrengthUserCardId.size() - 1);
			backUpUserCardId.add(backUp);
			System.out.println("将" + backUp + "添加到备份。");
			content = calculateContent(userCardId, toUseStrengthUserCardId);
			previewResult = httpRequestWithLogFile(_sid, "streng.php",
					"CardPreview", content, logFile);
			currentLevel = (int) Double.parseDouble(returnData(previewResult)
					.get("CardLevel").toString());
		}
		if (backUpUserCardId.size() > 0) {
			Long lastBackUp = backUpUserCardId
					.remove(backUpUserCardId.size() - 1);
			toUseStrengthUserCardId.add(lastBackUp);
		}

		System.out.println("准备开始升级，请确认：");
		String userConfirm = readLineFromConsole();
		if (!"y".equals(userConfirm)) {
			System.out.println("用户主动退出。");
			return;
		}
		content = calculateContent(userCardId, toUseStrengthUserCardId);
		Map strengthResult = httpRequestWithLogFile(_sid, "streng.php", "Card",
				content, logFile);
		System.out.println("强化结果：\n" + strengthResult);
	}

	private String readLineFromConsole() {
		if (System.console() != null) {
			return System.console().readLine();
		}
		Scanner scanner = new Scanner(System.in);
		return scanner.nextLine();
	}

	private Map returnData(Map result) {
		int status = ((Double) result.get("status")).intValue();
		if (status == 0) {
			System.out.println(result);
			System.exit(-1);
		}
		return (Map) result.get("data");
	}

	private String calculateContent(long userCardId1,
			List<Long> toUseStrengthUserCardId) {
		StringBuffer result = new StringBuffer();
		result.append("UserCardId1=");
		result.append(String.valueOf(userCardId1));
		result.append("&");
		result.append("UserCardId2=");
		for (Long id : toUseStrengthUserCardId) {
			result.append(id);
			result.append("_");
		}
		result.deleteCharAt(result.lastIndexOf("_"));
		return result.toString();
	}
}
